package com.example.a2209_shop.fg

import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.a2209_shop.R
import com.example.a2209_shop.adapter.ShopAdapter
import com.example.a2209_shop.database.DataBaseUtils
import com.example.a2209_shop.databinding.FragmentCarBinding
import com.example.a2209_shop.fgViewModel.CarViewModel
import com.example.base.mvvm.BaseFragment

class CarFragment : BaseFragment<FragmentCarBinding,CarViewModel>() {
    lateinit var shopAdapter:ShopAdapter

    override fun initData() {
        viewModel.selectSuccess.observe(this){
            if(it.code==200){
                shopAdapter.data.clear()
                shopAdapter.data.addAll(it.data)
                shopAdapter.notifyDataSetChanged()
            }
        }
        viewModel.addSuccess.observe(this){
            if(it.code==200){
                //添加购物车成功
                ToastUtils.showLong("修改购物车成功")
            }
        }
    }

    override fun initView() {
        shopAdapter = ShopAdapter()
        binding.rvCar.adapter = shopAdapter
        binding.rvCar.layoutManager = LinearLayoutManager(context)

        viewModel.selectCar()

        //添加子控件点击事件
        shopAdapter.addChildClickViewIds(R.id.car_cb,R.id.car_sub,R.id.car_add)
        shopAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.car_cb->{
                    //点击后，将当前的状态赋值给数据---获取原来的相反值
                    shopAdapter.data[position].isCheck = !shopAdapter.data[position].isCheck
                }
                R.id.car_sub->{
                    if(shopAdapter.data[position].count==1){
                        //删除购物车数据
                        AlertDialog.Builder(context)
                            .setTitle("提示")
                            .setMessage("确定删除吗")
                            .setNegativeButton("取消",null)
                            .setPositiveButton("确定",object :DialogInterface.OnClickListener{
                                override fun onClick(dialog: DialogInterface?, which: Int) {
                                    //执行删除操作
                                    viewModel.deleteCar(shopAdapter.data[position].id.toString())
                                    shopAdapter.data.removeAt(position)
                                    //局部刷新--不影响其他控件的状态
                                    shopAdapter.notifyItemRemoved(position)
                                }
                            })
                            .show()
                    }else{
                        shopAdapter.data[position].count--
                        (shopAdapter.getViewByPosition(position,R.id.car_count) as TextView).text = "${shopAdapter.data[position].count}"
                        viewModel.addCar(-1,shopAdapter.data[position].goods_id)
                    }
                }
                R.id.car_add->{
                    //页面数据进行加1  为了保持页面选中状态不发生变化   不刷新适配器   但适配器中的数据要发生变化
                    shopAdapter.data[position].count++
                    (shopAdapter.getViewByPosition(position,R.id.car_count) as TextView).text = "${shopAdapter.data[position].count}"
                    viewModel.addCar(1,shopAdapter.data[position].goods_id)
                }
            }
            //无论点击什么控件都可能会影响  金额和选中状态
            checkCb()
            checkAmont()
        }
        //底部全选按钮的点击事件
        binding.clCb.setOnCheckedChangeListener { buttonView, isChecked ->
            binding.clCb.setOnClickListener {
                //通过监听器 可以获取当前的选中的状态  将所有item的状态修改为当前状态   同时重新计算当前金额
                shopAdapter.data.forEach {
                    it.isCheck = isChecked
                }
                shopAdapter.notifyDataSetChanged()
                checkAmont()
            }
        }

        binding.etSearch.setOnClickListener {
            ARouter.getInstance().build("/app/CarSearchActivity").navigation()
        }
        //点击立即支付按钮，生成预下单状态的订单
        binding.clTopay.setOnClickListener {
            val list= mutableListOf<Boolean>()
            shopAdapter.data.forEach {
                list.add(it.isCheck)
            }
            if(true in list){
                //生成订单
                shopAdapter.data.forEach {
                    if(it.isCheck){
                        it.orderStatus = 1//预下单状态
                        DataBaseUtils.getDb().getOrderDao().insertOrder(it)
                    }
                }
                //跳转到支付界面
                ARouter.getInstance().build("/app/PayActivity").navigation(requireActivity(),200)
                //startActivityForResult()
            }else{
                ToastUtils.showLong("请选择商品")
            }
        }
    }

    private fun checkAmont() {
        var amount = 0//初始化金额为0
        //将选中状态的item 数量*单价  进行累加
        shopAdapter.data.forEach {
            if(it.isCheck){
                amount+=it.goods_default_price*it.count
            }
        }
        binding.clPrice.text = "合计：￥$amount"

    }

    private fun checkCb() {
        val flags = mutableListOf<Boolean>()
        shopAdapter.data.forEach {
            flags.add(it.isCheck)
        }
        if(false in flags){
            binding.clCb.isChecked = false
        }else{
            binding.clCb.isChecked = true
        }
        //binding.clCb.isChecked = false !in flags
    }

    override fun getViewModel() = CarViewModel::class.java

    override fun getLayout() = R.layout.fragment_car


   /* override fun onResume() {
        super.onResume()
        viewModel.selectCar()
        checkAmont()//重新计算金额
        checkCb()//重新计算全选
    }*/

}